package com.ddtech.framework.log.rest;

import com.ddtech.config.DataScope;
import com.ddtech.framework.log.service.LoginLogService;
import com.ddtech.framework.log.service.dto.LoginLogQueryCriteria;
import com.ddtech.framework.system.service.DeptService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.Set;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author bin_pu
 * @since 2020/5/9 14:06
 */
@Api(tags = "系统-登录日志")
@RestController
@RequestMapping("api")
public class LoginLogController {

    @Autowired
    private LoginLogService loginLogService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private DataScope dataScope;

    @GetMapping(value = "/loginLog")
    @PreAuthorize("hasAnyRole('ADMIN')")
    public ResponseEntity getLogs(LoginLogQueryCriteria criteria, Pageable pageable) {
        Set<String> deptSet = new HashSet<>();

        if (!ObjectUtils.isEmpty(criteria.getDeptId())) {
            deptSet.add(criteria.getDeptId());
            deptSet.addAll(dataScope.getDeptChildren(deptService.findByPid(criteria.getDeptId())));
            criteria.setDeptIds(deptSet);
        }
        return new ResponseEntity(loginLogService.queryAll(criteria, pageable), HttpStatus.OK);
    }
}
